import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Form, Button, Modal, Badge, Icon, DatePicker } from 'antd';
import { stringify } from 'qs';
import router from 'umi/router';
import moment from 'moment';
import ManageList from '@/components/ManageList';
import SelectForm from '@/components/SelectForm';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import StandardTable from '@/components/StandardTable';
import AntdDatePicker from '@/components/AntdDatePicker';
import AntdFormItem from '@/components/AntdFormItem';
import SearchSelect from '@/components/SearchSelect';
import AntdInput from '@/components/AntdInput';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import FileReader from '@/components/FileReader';
import FileImport from '@/components/FileImport';
import AntdForm from '@/components/AntdForm';
import AdModal from '@/components/AdModal';
// import ExportOSDetail from './ExportOSDetail';
import OrderAnalysisTableDetail from './OrderAnalysisTableDetail';
import { transferLanguage,getTimeDistance } from '@/utils/utils';

import {
  filterAddFile,
  filterDeteteFile,
  queryDict,
  vitifyCheck,
  formatPrice,
  formItemFragement,
  formateDateToMin,
} from '@/utils/common';
import prompt from '@/components/Prompt';
import { getQueryString } from '@/utils/common';
import {
  selectExportOSList,
  allDispatchType,
  routeUrl,
  renderTableAdSelect,
  //   allUrl,
  saveAllValues,
  statusList,
  containerSizeList,
  formateS,
  formate,
  KNTracksList_demo,
} from './utils';
// import styles from './exportOs.less';

const { confirm } = Modal;
// import { DatePicker } from 'antd';

const { RangePicker } = DatePicker;

@ManageList
@connect(({ myOrder, component, loading, i18n }) => ({
  KNTracksList: myOrder.KNTracksList,
  formValues: myOrder.formValues,
  searchValue: component.searchValue,
  dictObject: component.dictObject,
  loading: loading.effects[allDispatchType.list],
  language:i18n.language,
}))
@Form.create()
export default class ExportOSList extends Component {
  constructor(props) {
    super(props);
    const { form } = this.props;
    this.token = localStorage.getItem('token');
    this.userToken = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    this.state = {
      expandForm: false,
      detailId: '',
      selectedRows: [],
      importParams: { token: this.token },
      userType: this.userToken.type,
      orderNo: '',
      KNTracksList: {},
      statusShip: '',
      visible: false,
    };
    this.className = 'MyOrderList1';
    this.fileList = [];
  }

  componentWillMount() {}
  getSnapshotBeforeUpdate(prevProps, prevState) {
    const statusShip = getQueryString('statusShip');
  }

  componentDidMount() {
   this.getSelectList()
  }
  getSelectList = () => {
    const { formValues } = this.props;
    selectExportOSList({ props: this.props, payload: formValues });
  };
  checkInputText = val => {
    const checkList = {
      fuzyOrderNo: '订单号',
    };
    const checkArr = ['fuzyOrderNo'];
    //有值时校验：至少输入2位
    let tipsStr = [];
    let tips = '';
    checkArr.map(v => {
      if (val[v] && val[v].length < 2) {
        tipsStr.push(checkList[v]);
      }
    });
    if (tipsStr.length > 0) {
      tips = `查询时，${tipsStr.join('，')}至少输入2位`;
    }
    return tips;
  };
  /**
   * form 查找条件 重置
   */
  handleFormReset = () => {
    const { form } = this.props;
    const props = { props: this.props };
    saveAllValues({ payload: { formValues: {} }, ...props });
    selectExportOSList({ ...props });
  };

  /**
     * form 查找条件 查询
      // 订单编号 orderNumber (至少输入2位，全模糊)、 系统单号 ocsOrderNo (至少输入2位，全模糊)、
      // 提货（发货）地址 pickupDetailAddress (至少输入2位，全模糊)、 送货（收货）地址 deliveryDetailAddress (至少输入2位，全模糊)
     */
  handleSearch = formValues => {
    if (!formValues) return;
    const { exportTime, ...params } = formValues;
    if (exportTime && exportTime.length > 0) {
      params.beginTime = moment(exportTime[0]).format(formate);
      params.overTime = moment(exportTime[1]).format(formate);
    }
    const tipsText = this.checkInputText(formValues);
    if (tipsText) {
      prompt({
        content: tipsText,
        type: 'warn',
        duration: 3,
      });
      return;
    }
    saveAllValues({ payload: { formValues: params }, props: this.props });
    selectExportOSList({ props: this.props, payload: params });
  };

  /**
   * table 表格 分页操作
   */
  handleStandardTableChange = param => {
    return;
    const { formValues } = this.props;
    selectExportOSList({ payload: { ...formValues, ...param }, props: this.props });
  };

  handleStateChange = (options = []) => {
    options.map(item => {
      this.setState(item);
    });
  };
  openTrail = (e, id) => {
    this.setState({
      orderNo: id,
    });
    router.push({
      pathname: `${routeUrl.trailMap}`,
      query: {
        orderNo: id,
      },
    });
  };
  showDetail = (e, record) => {
    console.log("ExportOSList -> showDetail -> record", record)
    e.stopPropagation();
    this.handleStateChange([{ detailId: record['kangNingOrderNo'] }, { visible: true }]);
  };

  formatText = val => {
    if (val === '--------------------') {
      return '--';
    }
    return val;
  };

  render() {
    const {
      form,
      form: { getFieldDecorator },
      loading,
      isMobile,
      KNTracksList,
      language
    } = this.props;

    const { visible, detailId, selectedRows, expandForm, userType,  } = this.state;

    const commonParams = {
      getFieldDecorator,
    };
    const columns = [
      {
        title: 'Order No.',
        dataIndex: 'kangNingOrderNo',
        fixed: this.props.isMobile ? false : true,
        width: 100,
        // 27387 标红
        // render: (text, record) => (
        //   <a onClick={e => this.showDetail(e, record)} title={text}>
        //     {text}
        //   </a>
        // ),
        render: (text, record, index) => {
          const _text = (
            <a onClick={e => this.showDetail(e, record)} title={text}>
              {text}
            </a>
          );
          if (text == '27387') {
            return <div style={{ background: '#f5222d', width: 124, height: 20 }}>{_text}</div>;
          } else if (text == '27379') {
            return <div style={{ background: '#fadb14', width: 124, height: 20 }}>{_text}</div>;
          } else {
            return _text;
          }
        },
      },
      {
        title: transferLanguage('Analysis.field.OrderType',this.props.language),
        dataIndex: 'orderType',
        width: 100,
      },
      {
        title: transferLanguage('Analysis.field.Tracking',this.props.language),
        dataIndex: 'trail',
        width: 80,
        render: (text, record) => {
          return (
            <a title={'view Tracking'} onClick={e => this.openTrail(e, record.kangNingOrderNo)}>
              <Icon type="environment" />
            </a>
          );
        },
      },
      {
        title: transferLanguage('Analysis.field.Status',this.props.language),
        dataIndex: 'status',
      },
      {
        title: transferLanguage('Analysis.field.DeliveryNo',this.props.language),
        dataIndex: 'exportOrderNo',
        // render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
      },
      {
        title: transferLanguage('Analysis.field.TransportationNo',this.props.language),
       // title: '运输单号',
        dataIndex: 'transportOrderNo',
      },

      {
        title: transferLanguage('Analysis.field.OrderTime',this.props.language),
       // title: '下单时间',
        dataIndex: 'orderTime',
        render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
      },
      {
        title: transferLanguage('Analysis.field.RequiredDeliveryTime',this.props.language),
        //title: '要求发货时间',
        dataIndex: 'requiredDelivery',
        width: 150,
        render: text => <span title={text}>{text}</span>,
      },
      {
        title: transferLanguage('Analysis.field.PackTime',this.props.language),
        //title: '打包时间',
        dataIndex: 'packTime',
        render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
      },
      {
        title: transferLanguage('Analysis.field.PickTime',this.props.language),
        //title: '拣选时间',
        dataIndex: 'pickTime',
        render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
      },

      {
        title: transferLanguage('Analysis.field.Sender',this.props.language),
       // title: '发货人',
        dataIndex: 'sender',
        render: text => <span title={text}>{text}</span>,
      },
      {
        title: transferLanguage('Analysis.field.SendPlace',this.props.language),
        //title: '发货地',
        dataIndex: 'sendPlace',
        render: text => <span title={text}>{text}</span>,
      },
      {
        title: transferLanguage('Analysis.field.Receiver',this.props.language),
        //title: '收货人',
        dataIndex: 'receiver',
        width: 150,
        render: text => <span title={text}>{text}</span>,
      },
      {
        title: transferLanguage('Analysis.field.RequiredArrivalTime',this.props.language),
        //title: '要求到货时间',
        dataIndex: 'requiredArrivalTime',
        width: 150,
        render: text => <span title={text}>{text}</span>,
      },
      {
        title: transferLanguage('Analysis.field.ReceivePlace',this.props.language),
        //title: '收货地',
        dataIndex: 'receivePlace',
        width: 120,
        render: text => <span title={text}>{text}</span>,
      },
      {
        title: transferLanguage('Analysis.field.SignTime',this.props.language),
       // title: '签收时间',
        dataIndex: 'signTime',
        render: text => <span title={text}>{text}</span>,
      },
    ];

    const firstFormItem = (
      <AntdFormItem label={transferLanguage('Analysis.field.OrderNo',this.props.language)} code="fuzyOrderNo" {...commonParams}>
        <AntdInput />
      </AntdFormItem>
    );
    const secondFormItem = (
      <AntdFormItem label={transferLanguage('Analysis.field.OrderDate',this.props.language)} code="exportTime" {...commonParams}>
        <AntdDatePicker placeholder={['Start Date', 'End Date']} mode="range" />
      </AntdFormItem>
    );
    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      //   otherFormItem,
      form,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: expandForm => {
        this.handleStateChange([{ expandForm }]);
      },
    };

    const tableButtonsParams = {
      // handleAdd: this.handleAdd,
      // code: 'operate',
      //   pagination: KNTracksList_demo.pagination,
      buttons: <Fragment></Fragment>,
    };
    const rightDrawParams = {
      visible,
      title: transferLanguage('Analysis.field.OrderStatusDetails',this.props.language),
      width: '60%',
      closeDetail: () => {
        this.handleStateChange([{ visible: false }]);
      },
    };

    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        {/* <TableButtons /> */}

        <StandardTable
          loading={loading}
          data={KNTracksList}
          columns={columns}
          onPaginationChange={this.handleStandardTableChange}
          expandForm={expandForm}
          className={this.className}
          code="page"
          scrollX={1980}
        />
        <RightDraw {...rightDrawParams}>
          <OrderAnalysisTableDetail detailId={detailId} closeDetail={this.handleStateChange} />
        </RightDraw>
      </Fragment>
    );
  }
}
